import { defineStore } from "pinia";
import { loginAPI, logoutAPI } from "../api/user.ts";
import { RequestUser, User } from "../index";

const useUserStore = defineStore("user", {
  persist: true,
  state: () => {
    return {
      user: null as User | null,
    };
  },
  getters: {
    isLogin: (state): boolean => {
      return state.user !== null;
    },
    userName: (state): string => {
      if (state.user !== null) return state.user.username;
      return "未登录";
    },
    userID: (state): number | undefined => {
      return state.user?.id;
    },
    gradeID: (state) => {
      return state.user?.gradeID || 1;
    },
    isAdmin: (state) => {
      return state.user?.userIdentity === 1;
    },
  },
  actions: {
    login(user: RequestUser) {
      // const response = await loginAPI(user.id, user.password);
      return loginAPI(user.id, user.password)
        .then((response) => {
          if (response.status !== 200) {
            throw new Error("请求用户登录失败");
          }
          return response.data;
        })
        .then((result) => {
          if (result.code !== 0) {
            // throw new Error("登陆失败");
            return false;
          }
          this.user = result.data;
          // console.log(this.user);
          return true;
        });
    },
    logout() {
      logoutAPI().then(() => {
        this.user = null;
      });
    },
  }
});

export default useUserStore;
